//
//  AIInfoSetView.m
//  MiaMind
//
//  Created by Vill on 2023/12/14.
//

#import "AIInfoSetView.h"
#import "AIGradientTabView.h"
#import "AIInfoFirstTableCell.h"
#import "AIInfoSecondTableCell.h"
#import "AIInfoThirdTableCell.h"
#import "AIInfoFourTableCell.h"
#import "AIInfoChatView.h"      // 消息view
#import "AIBirthdayTableCell.h"    // 生日cell
#import "AIRegisterDataSetModel.h"  // 基础资料编辑模型
#import "AIOtherDataListCell.h"

@interface AIInfoSetView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *closeBtn;  //关闭
@property (nonatomic, strong) UIView *botoomView;
@property (nonatomic, strong) UIVisualEffectView *blurView;
@property (nonatomic, strong) AIGradientTabView *tableView;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) AIInfoChatView *messageView;
@property (nonatomic, assign) NSInteger selectedSection;
@property (nonatomic, assign) NSInteger selectedRow;
@property (nonatomic, copy) NSString *selectAiId;  //选择的AI模型id
@property (nonatomic, strong) UIButton *nextBtn;   //下一步

@property (nonatomic, strong) NSString *selectName;     // 设置的昵称
@property (nonatomic, strong) NSString *selectBirthday; // 设置的生日
@property (nonatomic, strong) NSString *selectSex;      // 设置的性别

@property (nonatomic, strong) NSMutableArray *otherDataArr; //数组
@property (nonatomic, strong) NSMutableArray *selectListArr; //选择的数组

@end

@implementation AIInfoSetView

// 数据列表
- (NSMutableArray *)otherDataArr{
    if(!_otherDataArr){
        _otherDataArr = [NSMutableArray array];
    }
    return _otherDataArr;
}

// 选择的数组
- (NSMutableArray *)selectListArr{
    if(!_selectListArr){
        _selectListArr = [NSMutableArray array];
    }
    return _selectListArr;
}

- (AIInfoChatView *)messageView{
    if(!_messageView){
        _messageView = [[AIInfoChatView alloc] initWithFrame:CGRectZero];
        _messageView.backgroundColor = UIColor.clearColor;
    }
    return _messageView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if(self == [super initWithFrame:frame]){
        [self getInfoSetList];
        self.selectSex = @"Female";
    }
    return self;
}

- (void)getInfoSetList{
    [SVProgressHUD show];
    [AIManager requestMethod:@"GET" url:api_allOtherData parameters:@{} successBlock:^(id  _Nullable result) {
        [self.otherDataArr removeAllObjects];
        NSArray *tempArr = result;
        NSMutableArray *strArr = [NSMutableArray arrayWithObjects:
                              [NSMutableArray arrayWithObjects:@"NickName", nil],
                              [NSMutableArray arrayWithObjects:@"Birthday", nil],
                              [NSMutableArray arrayWithObjects:@"Sexcy", nil],
                              nil];
        if (tempArr.count > 0){
            for (int i = 0; i<tempArr.count; i++) {
                AIRegisterDataSetModel *datamodel = [AIRegisterDataSetModel mj_objectWithKeyValues:tempArr[i]];
                [self.otherDataArr addObject:datamodel];
                NSMutableArray *modelArr = [NSMutableArray array];
                [modelArr addObject:datamodel.name];
                [strArr addObject:modelArr];
            }
        }
        [SVProgressHUD dismiss];
        self.listArray = strArr;
        [self setUi];  //设置UI
    } failedBlock:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
    } showHUD:NO];
}

-(void)setUi{
    self.selectedSection = -1;
    self.selectedRow = -1;

    [self addSubview:self.closeBtn];
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(34));
        make.trailing.mas_equalTo(self).mas_offset(-PTW(13));
        make.top.mas_equalTo(self).mas_offset(KStatusBarHeight);
    }];
    [self addSubview:self.botoomView];
    [self.botoomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self);
        make.height.mas_equalTo(PTW(400)+KBottomSafeHeight);
    }];
    [self.botoomView addSubview:self.blurView];
    [self.blurView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.botoomView);
    }];
    [self.botoomView addSubview:self.nextBtn];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(PTW(170), PTW(84)));
        make.centerX.mas_equalTo(self);
        make.bottom.mas_equalTo(self).mas_offset(-KBottomSafeHeight);
    }];
    [self.botoomView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.mas_equalTo(self.botoomView);
        make.bottom.mas_equalTo(self.nextBtn.mas_top);
    }];
    
    [self addSubview:self.messageView];
    [self.messageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self).mas_offset(PTW(125));
        make.trailing.mas_equalTo(self).mas_offset(-PTW(25));
        make.top.mas_equalTo(self.closeBtn.mas_bottom).mas_offset(PTW(25));
        make.bottom.mas_equalTo(self.botoomView.mas_top).mas_offset(-PTW(10));
    }];
}

// 选中的AI人物id
- (void)setChooseAiId:(NSString *)chooseAiId{
    _chooseAiId = chooseAiId;
    self.selectAiId = chooseAiId;
}

#pragma mark ------------------- lazy ------------------
- (UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:KImaged(@"ai_main_close") forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

- (UIView *)botoomView{
    if(!_botoomView){
        _botoomView = [UIView new];
        _botoomView.backgroundColor = UIColor.clearColor;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self->_botoomView clipsCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:PTW(20)];
        });
    }
    return _botoomView;
}

- (UIVisualEffectView *)blurView{
    if(!_blurView){
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        _blurView.alpha = 0.6;
        _blurView.backgroundColor = [UIColor colorHex:@"#FFFFFF" alpha:0.2];
    }
    return _blurView;
}

- (AIGradientTabView *)tableView{
    if(!_tableView){
        _tableView = [[AIGradientTabView alloc] initWithFrame:CGRectMake(0,KScreenHeight - PTW(400) - KTabBarHeight, KScreenWidth, PTW(400)+KTabBarHeight) direction:AIGradualDirectionTop gradualValue:@.1f];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

// 下一步
- (UIButton *)nextBtn{
    if(!_nextBtn){
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setBackgroundImage:KImaged(@"ai_regis_next") forState:UIControlStateNormal];
        [_nextBtn setTitle:@"Next" forState:UIControlStateNormal];
        [_nextBtn setTitleColor:[UIColor colorHex:@"#5C5C5C"] forState:UIControlStateNormal];
        _nextBtn.titleLabel.font = [UIFont fontWithWeight:MTBold size:PTW(15)];
        [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
        _nextBtn.enabled = NO;
    }
    return _nextBtn;
}

- (void)closeAction:(UIButton*)btn{
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        if (self.closeClickBlock){
            self.closeClickBlock();
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionArr = self.listArray[section];
    return sectionArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        AIInfoFirstTableCell *cell = [AIInfoFirstTableCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([self.selectName strHasValue]){
            cell.titLbl.text = self.selectName;
        }
        WeakSelf(self);
        cell.textfieldEndEditBlock = ^(NSString * _Nonnull nameStr) {
            if (nameStr.length > 0){
                weakself.selectName = nameStr;
                [weakself btnValuechange];
            }
        };
        return cell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0){
            AIInfoSecondTableCell *cell = [AIInfoSecondTableCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if ([self.selectBirthday strHasValue]){
                cell.birthLbl.text = self.selectBirthday;
            }
            if (self.selectedSection == indexPath.section){
                // 如果箭头未旋转，则进行旋转
                [UIView animateWithDuration:0.3 animations:^{
                    cell.arrowBtn.transform = CGAffineTransformMakeRotation(M_PI_2);
                }];
            }else{
                [UIView animateWithDuration:0.3 animations:^{
                    cell.arrowBtn.transform = CGAffineTransformIdentity;
                }];
            }
            return cell;
        }else{
            AIBirthdayTableCell *cell = [AIBirthdayTableCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            WeakSelf(self);
            cell.selectBirthdayBlock = ^(NSString * _Nonnull birthday) {
                if (birthday.length > 0){
                    weakself.selectBirthday = birthday;
                    [weakself btnValuechange];
                }
                [weakself deleteSelectRowsIndexPath:indexPath];
            };
            return cell;
        }
    }else if(indexPath.section == 2){
        AIInfoThirdTableCell *cell = [AIInfoThirdTableCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.chooseStr = self.selectSex;
        WeakSelf(self);
        // 性别选择
        cell.sexSelectBlock = ^(NSString * _Nonnull chooseSex) {
            weakself.selectSex = chooseSex;
        };
        return cell;
    }else{
        if (indexPath.row == 0){
            AIInfoFourTableCell *cell = [AIInfoFourTableCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.listTitle.text = self.listArray[indexPath.section][0];
            if (self.selectedSection == indexPath.section){
                // 如果箭头未旋转，则进行旋转
                [UIView animateWithDuration:0.3 animations:^{
                    cell.arrowBtn.transform = CGAffineTransformMakeRotation(M_PI_2);
                }];
            }else{
                [UIView animateWithDuration:0.3 animations:^{
                    cell.arrowBtn.transform = CGAffineTransformIdentity;
                }];
            }
            if (self.selectListArr > 0){
                for (NSMutableArray *tempArr in [self.selectListArr copy]) {
                    for (int i = 0; i<tempArr.count; i++) {
                        NSIndexPath *tempIndex = tempArr[2];
                        if (tempIndex.section == indexPath.section){
                            cell.listTitle.text = tempArr[1];
                            cell.listTitle.textColor = UIColor.whiteColor;
                        }
                    }
                }
            }
            return cell;
        }else{
            AIOtherDataListCell *cell = [AIOtherDataListCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.dataSetModel = self.otherDataArr[indexPath.section - 3];
            WeakSelf(self);
            // 教育背景选择
            cell.otherDataSelectBlock = ^(NSString * _Nonnull dataTitleId, NSString * _Nonnull selectName) {
                [weakself addOthersDataWithID:dataTitleId content:selectName andIndexPath:indexPath];
                [weakself deleteSelectRowsIndexPath:indexPath];
            };
            return cell;
        }
    }
}

// 添加选择的数组
- (void)addOthersDataWithID:(NSString *)dataId content:(NSString *)content andIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *arr  = [NSMutableArray array];
    [arr addObject:dataId];
    [arr addObject:content];
    [arr addObject:indexPath];
    [self.selectListArr addObject:arr];
    // 遍历主数组
    for (NSInteger i = self.selectListArr.count - 1; i >= 0; i--) {
        NSMutableArray *currentArray = self.selectListArr[i];
        // 遍历前面的子数组
        for (NSInteger j = i - 1; j >= 0; j--) {
            NSMutableArray *compareArray = self.selectListArr[j];
            // 检查当前子数组是否包含与前面子数组相同的元素
            BOOL containsSameElement = NO;
            for (NSString *element in currentArray) {
                if ([compareArray containsObject:element]) {
                    containsSameElement = YES;
                    break;
                }
            }
            // 如果包含相同元素，则移除前面的子数组
            if (containsSameElement) {
                [self.selectListArr removeObjectAtIndex:j];
                i--;
            }
        }
    }
    // 打印结果
//    NSLog(@"all list ---- %@", self.selectListArr);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 4 || indexPath.section == 5 ) && indexPath.row == 0){
        return PTW(73);
    }else{
        if (indexPath.section == 1 && indexPath.row == 1){
            return 225;
        }else{
            return 200;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 移除上次插入的行
    [self deleteSelectRowsIndexPath:indexPath];
}

// 移除上次插入的行
- (void)deleteSelectRowsIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 2){
        // 移除上次插入的行
        if (self.selectedSection >= 0 && self.selectedSection != indexPath.section) {
           [self.listArray[self.selectedSection] removeObjectAtIndex:self.selectedRow];
           [self.tableView reloadData];
           self.selectedSection = -1;
           self.selectedRow = -1;
        }
        return;
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectedSection == indexPath.section && self.selectedRow == indexPath.row) {
       // 点击刚才插入的行，移除该行
       [self.listArray[indexPath.section] removeObjectAtIndex:indexPath.row];
       self.selectedSection = -1;
       self.selectedRow = -1;
       [self.tableView reloadData];
       return;
    }
    // 移除上次插入的行
    if (self.selectedSection >= 0 && self.selectedSection != indexPath.section) {
       [self.listArray[self.selectedSection] removeObjectAtIndex:self.selectedRow];
       [UIView performWithoutAnimation:^{
           [self.tableView reloadData];
       }];
    }
    if (self.selectedSection == indexPath.section) {
       // 点击同一组，移除刚才插入的行
       [self.listArray[indexPath.section] removeObjectAtIndex:self.selectedRow];
       self.selectedSection = -1;
       self.selectedRow = -1;
    } else {
       // 插入新的行
       [self.listArray[indexPath.section] addObject:@"Inserted Row"];
       self.selectedSection = indexPath.section;
       self.selectedRow = indexPath.row + 1;
    }
    [UIView performWithoutAnimation:^{
        [self.tableView reloadData];
    }];
    if (self.selectedSection >=0 ){
        NSIndexPath *showIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        [self.tableView beginUpdates];
        [self.tableView scrollToRowAtIndexPath:showIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        [self.tableView endUpdates];
        NSLog(@"selected ----- %ld -- %ld",(long)self.selectedSection,(long)self.selectedRow);
    }else{
        [self.tableView beginUpdates];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        [self.tableView endUpdates];
    }
}

#pragma mark --------- next按钮  --------
-(void)nextAction:(UIButton *)sender{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([self.selectName strHasValue]){
        dic[@"nickName"] = self.selectName;
    }
    if ([self.selectBirthday strHasValue]){
        dic[@"birthday"] = self.selectBirthday;
    }
    if ([self.selectSex strHasValue]){
        if ([self.selectSex isEqualToString:@"Female"]){
            dic[@"sexType"] = @"WOMAN";
        }else if ([self.selectSex isEqualToString:@"Male"]){
            dic[@"sexType"] = @"MAN";
        }else{
            dic[@"sexType"] = @"UNKNOWN";
        }
    }
    if (self.selectListArr > 0){
        NSMutableArray *otherDatasArr = [NSMutableArray array];
        for (int i= 0; i<self.selectListArr.count; i++) {
            NSMutableDictionary *otherDatasDic = [NSMutableDictionary dictionary];
            NSString *dataTitleId = self.selectListArr[i][0];
            NSString *content = self.selectListArr[i][1];
            otherDatasDic[@"dataTitleId"] = dataTitleId;
            otherDatasDic[@"content"] = content;
            [otherDatasArr addObject:otherDatasDic];
        }
        dic[@"otherDatas"] = otherDatasArr;
    }
    dic[@"chatAiId"] = self.selectAiId;
    NSLog(@"----- %@",dic);
    if (self.nextActionBlock){
        self.nextActionBlock(dic);
    }
}

// 下一步按钮状态修改
- (void)btnValuechange{
    if ([self.selectName strHasValue] && [self.selectBirthday strHasValue]){
        self.nextBtn.enabled = YES;
    }
}

@end
